<?php
/**
 * This file is part of easycrm, created by PhpStorm.
 * Author: LouXin
 * Date: 2015/2/16 10:35
 * File: ElasticsearchModel.php
 */

namespace Icsoc\CustomReportBundle\Model;

use Elasticsearch\Client;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ElasticsearchModel
{
    protected $container;
    protected $client;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $hosts = $this->container->getParameter('elasticsearch_hosts');
        $this->client = new Client(array(
            'hosts' => $hosts,
            'logging' => false
        ));
    }

    /**
     * 添加数据到Elasticsearch中
     *
     * @param string $id 索引的ID
     * @param array $data 数据
     * @param string $type Elasticsearch的type
     * @param string $index Elasticsearch的index
     *
     * @return bool|array 成功返回数据，失败返回false
     */
    public function addDataToElasticsearch($id, array $data, $type = 'tmp_logs', $index = 'icsoc')
    {
        if (empty($id) || empty($data)) {
            return false;
        }

        $params = array(
            'index' => $index,
            'type' => $type,
            'id' => $id,
            'refresh' => true,
            'body' => $data
        );

        return $this->client->index($params);
    }
}
